<?php
$image = trim(strip_tags($_GET["image"]));
$width_max = intval(($_GET["wmax"] != "") ? $_GET["wmax"] : 500);
$height_max = intval(($_GET["hmax"] != "") ? $_GET["hmax"] : 500);
$quality = intval(($_GET["quality"] != "") ? $_GET["quality"] : 100);

$save = ($_GET["save"] != "") ? true : false;
$handle = fopen($image, "r");

if ($handle == null) {
	exit;
}

$picture = fread($handle, filesize($image));
fclose($handle);

if ($picture != "" && $picture != null)
{
	header("content-type: image/jpeg");

	$source = imagecreatefromstring($picture);
	$original_width = imagesx($source);
	$original_height = imagesy($source);

	if ($original_width > $width_max || $original_height > $height_max)
	{
		$thumb_width = $width_max;
		$thumb_height = $height_max;

		if ($thumb_width / $original_width * $original_height > $thumb_height)
		{
			$thumb_width = round($thumb_height * $original_width / $original_height);
		}
		else
		{
			$thumb_height = round($thumb_width * $original_height / $original_width);
		}
	}
	else
	{
		$thumb_width = $original_width;
		$thumb_height = $original_height;
	}

	if (!@$bgcol)
	{
		$thumb = imagecreatetruecolor($thumb_width, $thumb_height);
		imagecopyresampled($thumb, $source, 0, 0, 0, 0, $thumb_width, $thumb_height, $original_width, $original_height);
	}
	else
	{
		$thumb = imagecreatetruecolor($width_max, $height_max);
		imagefilledrectangle($thumb, 0, 0, $width_max - 1, $height_max - 1, intval($bgcol, 16));
		imagecopyresampled($thumb, $source, round(($width_max - $thumb_width) / 2), round(($height_max - $thumb_height) / 2), 0, 0, $thumb_width, $thumb_height, $original_width, $original_height);
	}

	$filename = ($save == true) ? date("YmdHis", time()) . ".jpg" : "";
	imagejpeg($thumb, $filename, $quality);
	imagedestroy($thumb);
}
else
{
	echo "";
}
?>